package work.MrSun.xyq.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import work.MrSun.xyq.model.WXSessionModel;
import work.MrSun.xyq.model.XyqUser;
import work.MrSun.xyq.service.XyqUserService;
import work.MrSun.xyq.util.common.HttpClientUtil;
import work.MrSun.xyq.util.common.JsonUtils;
import work.MrSun.xyq.util.login.IsLogin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录的实现
 */
@RestController
public class LoginController {
    @Autowired
    private XyqUserService xyqUserService;

    /**
     * 登录功能
     *
     * @param code
     * @return
     */
    @Transactional
    @PostMapping("/Login")
    public IsLogin Login(String code, @RequestBody XyqUser xyqUser) {

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String, String> param = new HashMap<String, String>();
        param.put("appid", "wx3114fb2f60c744da");
        param.put("secret", "6e7ed959071cb7b32a44afa42076ca24");
        param.put("js_code", code);
        param.put("grant_type", "authorization_code");


        String wxResult = HttpClientUtil.doGet(url, param);
        WXSessionModel wxSessionModel = JsonUtils.jsonToPojo(wxResult, WXSessionModel.class);

        String openid = wxSessionModel.getOpenid();
        xyqUser.setUserOpenid(openid);

        return new IsLogin().isTrue(xyqUser, openid, xyqUserService);
    }

    @PostMapping("/checkAdmin")
    public List<XyqUser> checkAdmin(Integer id) {
        XyqUser mangoUser = new XyqUser();
        mangoUser.setUserId(id);
        return xyqUserService.getUserMessageByOtherMessage(mangoUser);
    }
}
